package servlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/*
 * Used to upload file with timetable, after its process redirects to ApplicationServlet.
 */
public class FileUploadServlet extends HttpServlet {
    private static String uploadedFilePath;
    
    public static void setUploadedFilePath() {
        uploadedFilePath = ApplicationServlet.getServletPath() + File.separator + "timetable.xml";
    }
    
    public static String getUploadedFilePath() {
        return uploadedFilePath;
    }
    

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession(false);
        
        String userRole;
        if (session == null || (userRole = (String) session.getAttribute("userRole")) == null || !userRole.equals("admin")) {            
            System.err.println("Error occured during file upload.");
            // Send 404 error code.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        // request must be multipart
        if (!ServletFileUpload.isMultipartContent(request)) {
            System.err.println("Error occured during file upload.");
            // Send 404 error code.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        Integer classId = null;
        boolean fileSaved = false;
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
                        
        try {
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
            // iterate over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // process classId field
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    if (fieldName.equals("classId")) {
                        classId = Integer.valueOf(item.getString());
                    }
                } else {
                    String fieldName = item.getFieldName();
                    if (fieldName.equals("file")) {
                        // save the file on disk
                        File uploadedFile = new File(uploadedFilePath);
                        item.write(uploadedFile);
                        item.delete();
                        fileSaved = true;
                    }
                }
            }
        } catch (Exception exception) {
            System.err.println("Error occured during file upload.");
            // Send 404 error code.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        if (classId != null && fileSaved) {
            response.sendRedirect("/gradebook/gradebook?content=setTimetable&classId=" + classId.intValue()); 
        } else {
            System.err.println("Error occured during file upload.");
            // Send 404 error code.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }
}
